﻿using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Repository;
using JinfuyuanProject.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using JinfuyuanProject.Entity;

namespace JinfuyuanProject.Service.Service
{
    public class PaySalaryService : IPaySalaryService
    {
        private readonly ISalaryRepository _salaryRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IStaffRepository _staffRepository;
        private readonly ISalaryDetailsRepository _salaryDetailsRepository;
        private readonly IContractRepository _contractRepository;

        public PaySalaryService(ISalaryRepository SalaryRepository, IStaffRepository staffRepository, IRoleRepository roleRepository, ISalaryDetailsRepository salaryDetailsRepository,IContractRepository contractRepository) {

            _salaryRepository = SalaryRepository;
            _roleRepository = roleRepository;
            _staffRepository = staffRepository;
            _salaryDetailsRepository = salaryDetailsRepository;
            _contractRepository = contractRepository;
        }
        public async Task Execute()
        {
             await Task.Run(async () =>
            {
                // 这里是执行薪资发放的逻辑
                //先通过当前时间获取当前年份月份（每月15号）
                //从数据库Salary表中获取当前年份月份从上个月15号到这个月15号所有员工的薪资信息
                //遍历所有员工的薪资信息
                //计算当前年份月份从上个月15号到这个月15号的考勤天数（除去周六周日都是工作日）
                //联合员工表和角色表获取Salary表中员工的基本工资（BaseSalary），Proportion提成比例
                //根据考勤天数（Attendance）和工作天数（WorkDays）和基本工资计算出当前年份月份从上个月15号到这个月15号的应发基本薪资（BaseMoney）=（BaseSalary/Attendance）*WorkDays
                //联合薪资明细表（薪资表员工id==薪资明细表员工id （当前年份月份从上个月15号到这个月15号））获取该员工当前年份月份从上个月15号到这个月15号的提成薪资（ExtraMoney）=薪资明细表中CommissionMoney字段
                //更新薪资明细表的薪资表id（SalaryId）=薪资表id
                // 获取当前时间
                var startDate = DateTime.Now;
                var endDate= DateTime.Now;
            // 获取上个月15号到本月15号的日期范围
            if (startDate.Month == 1)
                {
                    startDate = new DateTime(startDate.Year - 1, 12,0);
                    endDate = new DateTime(endDate.Year, endDate.Month + 1, 1);
                }
               else
                    startDate = new DateTime(startDate.Year, startDate.Month - 1, 1);
                endDate = new DateTime(endDate.Year, endDate.Month, 1);
                // 获取从上个月15号到这个月15号的所有员工薪资信息
                var salaryRecords = await _salaryRepository.GetSalariesAsync(startDate, endDate);

            // 遍历员工薪资信息
            foreach (var salary in salaryRecords)
            {
                    // 计算考勤天数，排除周六周日
                    salary.Attendance = GetWorkDays(startDate, endDate);

                // 获取员工的基本信息
                var employee = await _staffRepository.GetEmployeeByIdAsync((int)salary.EmpId);
                var role = await _roleRepository.GetRoleByIdAsync((int)employee.RoleId);
                salary.BaseSalary = role.BaseSalary;
                salary.Proportion=role.Proportion;
                    // 计算应发基本薪资
                    decimal baseMoney = (decimal)(role.BaseSalary / salary.Attendance) * (int)salary.WorkDays;

                    // 获取该员工的提成薪资
                    // 获取员工合同
                    var contractlist = await _contractRepository.GetContractByEmployeeIdAsync(employee.Id, startDate, endDate);
                    decimal extraSalary=0;
                    if (contractlist.Count>0)
                    {
                        foreach (var contract in contractlist)
                        {
                            // 基于合同ID获取薪资明细
                            var salaryDetail = await _salaryDetailsRepository.GetSalaryDetailAsync(contract.Id, startDate, endDate);

                            if (salaryDetail != null)
                            {
                                salaryDetail.SalaryId = salary.Id;
                                extraSalary += salaryDetail.CommissionMoney;
                                await _salaryDetailsRepository.SaveSalaryDetailAsync(salaryDetail);
                            }
                        }
                    }

                    // 更新薪资信息
                    salary.BaseMoney = baseMoney;
                    salary.ExtraSaraly = extraSalary;
                    salary.TotalSaraly = baseMoney + extraSalary;
                    salary.Times = DateTime.Now;
                    salary.IsDelete = 0;
                    // 保存更新
                    await _salaryRepository.SaveSalaryAsync(salary);
                }
        });
        }

        // 计算工作天数，排除周末
        private int GetWorkDays(DateTime startDate, DateTime endDate)
        {
            int workDays = 0;
            for (DateTime date = startDate; date <endDate; date = date.AddDays(1))
            {
                if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
                {
                    workDays++;
                }
            }
            return workDays;
        }
    }
    
}
